﻿@model LocalPluginsModel
@using Newtonsoft.Json;
@{
    //page title
    ViewBag.Title = T("Admin.Configuration.Plugins").Text;

    var allPluginsSelectList = Model.AllPlugins.Select(x => new SelectListItem { Value = x.SystemName, Text = x.FriendlyName });
    var availableSites = JsonConvert.SerializeObject(Model.AvailableSites.Select(x => new { value = x.Id, text = x.Name }).ToArray());

    //Html.AddCssFileParts(true, "~/Content/x-editable/bootstrap-editable.css");
    //Html.AppendScriptParts(true, "~/Content/x-editable/bootstrap-editable.js");
}
@helper PluginList(IEnumerable<PluginModel> plugins)
{
    foreach (var plugin in plugins)
    {
        <div class="module-item@(!plugin.Installed ? " inactive" : "") clearfix" data-system-name="@plugin.SystemName" data-friendly-name="@plugin.FriendlyName">
            <div class="module-icon">
                <img class="icon img-responsive" src="@Url.Content(plugin.IconUrl)" />
            </div>
            <div class="module-data module-data-cols-2 clearfix@(!plugin.Installed ? " inactive" : "")">
                <!-- General -->
                <div class="module-col">
                    <div>
                        <span class="module-name">
                            @plugin.FriendlyName
                        </span>
                        @if (plugin.Installed)
                        {
                        <span class="label label-warning">@T("Admin.Configuration.Plugins.Fields.Installed")</span>
                        }
                    </div>
                    <div class="module-info">
                        @if (plugin.Author.HasValue())
                        {
                        <span class="attr-name">@T("Admin.Configuration.Plugins.Fields.Author"):</span>
                        <span class="attr-value">@plugin.Author</span>
                        }
                        <span class="attr-name">@T("Admin.Configuration.Plugins.Fields.Version"):</span>
                        <span class="attr-value">@plugin.Version</span>
                        <span class="attr-name">@T("Admin.Configuration.Plugins.Fields.SystemName"):</span>
                        <span class="attr-value">@plugin.SystemName</span>
                    </div>
                    @if (plugin.Description.HasValue())
                    {
                    <div class="module-description">
                        @plugin.Description
                    </div>
                    }
                    @if (@Model.AvailableSites.Count > 1)
                    {
                    <div style="margin: 4px 0;">
                        <span>@T("Admin.Common.Site.LimitedTo"): </span>
                        <a href="#" data-pk='@plugin.SystemName' data-value='[@String.Join(",", plugin.SelectedSiteIds)]' class="editable editable-click site-limiter">
                            <!-- AJAX -->
                        </a>
                    </div>
                    }
                    @if (plugin.Installed)
                    {
                    <div class="module-actions">
                        <div class="btn-group">
                            <a class="btn btn-default btn-sm plugin-update-resources" href="@Url.Action("UpdateStringResources", new { systemName = plugin.SystemName })">
                                <i class="fa fa-language"></i>
                                @T("Admin.Configuration.Plugins.Resources.Update")
                            </a>
                            @if (plugin.ConfigurationUrl.HasValue())
                                {
                                <a class="btn btn-default btn-sm plugin-configure" href="@plugin.ConfigurationUrl">
                                    <i class="fa fa-cog"></i>
                                    @T("Admin.Configuration.Plugins.Fields.Configure")
                                </a>
                                }
                        </div>
                    </div>
                    }
                </div>
                <!-- Buttons -->
                <div class="module-col">
                    @if (plugin.Installed)
                    {
                    <a class="btn btn-default plugin-uninstall" data-toggle="button" href="#">
                        @T("Admin.Configuration.Plugins.Fields.Uninstall")
                    </a>
                    }
                    else
                    {
                    <a class="btn btn-success plugin-install" data-toggle="button" href="#">
                        <i class="fa fa-arrow-circle-o-down"></i>
                        @T("Admin.Configuration.Plugins.Fields.Install")
                    </a>
                    }
                </div>
            </div>
        </div>
    }
}
@using (Html.BeginForm("ExecuteTasks", null, FormMethod.Post, new { id = "plugins-form" }))
{
    @Html.DropDownList("pluginsToInstall", allPluginsSelectList, new { @class = "hide", multiple = "multiple" })
    @Html.DropDownList("pluginsToUninstall", allPluginsSelectList, new { @class = "hide", multiple = "multiple" })

    <div class="row">
        <div class="col-md-12">
            <div class="portlet light">
                <div class="section-header sticky">
                    <div class="caption">
                        <i class="icon-equalizer font-red-sunglo"></i>
                        <span class="caption-subject font-red-sunglo bold uppercase">@T("Admin.Configuration.Plugins") </span>
                        <span class="caption-helper"></span>
                    </div>

                    <div class="actions">
                        <button id="btn-execute-tasks" type="submit" class="btn btn-default" disabled="disabled">
                            <i class="fa fa-cogs"></i>
                            @T("Admin.Configuration.Plugins.ExecuteTasks")
                            <span class="label label-danger label-uninstall-count hide">0</span>
                            <span class="label label-warning label-install-count hide">0</span>
                        </button>
                        <a id="uploadpackage" href="#uploadpackage-window" data-toggle="modal" class="btn btn-default" role="button">
                            <i class="fa fa-upload"></i>
                            @T("Admin.Packaging.UploadPlugin")
                        </a>
                        <div class="btn-group" style="vertical-align: middle">
                            <a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">
                                @T("Admin.Common.Edit")
                                <span class="fa fa-caret-down"></span>
                            </a>
                            <ul class="dropdown-menu pull-right">
                                <li>
                                    <a href="@Url.Action("ReloadList")">
                                        <i class="fa fa-refresh"></i>
                                        @T("Admin.Configuration.Plugins.ReloadList")
                                    </a>
                                </li>
                                <li>
                                    <a href="@Url.Action("UpdateAllStringResources")" class="plugin-update-allresources">
                                        <i class="fa fa-refresh"></i>
                                        @T("Admin.Configuration.Plugins.Resources.UpdateAll")
                                    </a>
                                </li>
                            </ul>
                        </div>
                        <div class="portlet-input input-inline input-medium">
                            <div class="portlet-input input-inline input-small">
                                <div class="input-icon right">
                                    <i class="icon-magnifier"></i>
                                    @Html.TextBox("filter-query", "", new { @class = "form-control input-sm", style = "margin: 0;", placeholder = T("Common.Search").Text })
                                </div>
                            </div>


                        </div>
                    </div>
                </div>
                <div class="portlet-body form form-horizontal form-bordered form-row-stripped" id="local-plugins">
                    <div class="alert alert-info fade in">
                        <button class="close" data-dismiss="alert">x</button>
                        <h4>@T("Admin.Configuration.Plugins.Description")</h4>
                        <ol>
                            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step1", "uploadpackage", "#uploadpackage-window"))</li>
                            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step2"))</li>
                            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step3"))</li>
                            <li>@Html.Raw(T("Admin.Configuration.Plugins.Description.Step4"))</li>
                        </ol>
                    </div>
                    <div class="form-body">
                        @foreach (var g in Model.Groups.OrderBy(x => x.Key))
                        {
                            <div class="module-list">
                                <h3>@g.Key</h3>
                                @PluginList(g.Value)
                            </div>
                        }
                        <input type="submit" id="btnRefresh" name="btnRefresh" style="display: none" />
                    </div>
                </div>
            </div>
        </div>
    </div>
}
<script type="text/javascript">
    $(document).ready(function () {

        var sites = @Html.Raw(availableSites);

        // Multisite
        $(".site-limiter").editable({
            type: 'checklist',
            title: '@T("Admin.Common.Site.AvailableFor")',
            url: '@Url.Action("SetSelectedSites")',
            source: sites,
            unsavedclass: null,
            placement: "right",
            emptytext: '@T("Common.No")',
            autotext: 'always',
            display: function (value, sourceData) {
                //display checklist as comma-separated values
                var html = [],
					checked = $.fn.editableutils.itemsByValue(value, sourceData);

                if (checked.length) {
                    $.each(checked, function (i, v) { html.push($.fn.editableutils.escape(_.str.truncate(v.text, 40))); });
                    $(this).html(html.join(', '));
                } else {
                    $(this).empty();
                }
            }
        });

        function getPluginFriendlyName(dropdown, systemName) {
            return dropdown.find('option[value="{0}"]'.format(systemName)).text();
        }

        var dropdownInstall = $('#pluginsToInstall'),
            dropdownUninstall = $('#pluginsToUninstall'),
            btnExecuteTasks = $('#btn-execute-tasks');

        // Execute filtering
        var mainContainer = $('#local-plugins');
        $('#filter-query').on('keyup', function (e) {
            var el = $(this);

            // Retrieve the input field text and reset the count to zero
            var filter = el.val(),
                rg = new RegExp(filter, "i");

            // Loop through the plugin items
            $('.module-list').each(function () {
                var group = $(this),
                    count = 0;

                group.find('.module-item').each(function () {
                    // If the list item does not contain the text phrase hide it
                    if (filter.length > 1 && $(this).data('system-name').search(rg) < 0 && $(this).data('friendly-name').search(rg) < 0) {
                        $(this).hide();
                    }
                        // Show the list item if the phrase matches and increase the count by 1
                    else {
                        $(this).show();
                        count++;
                    }
                });

                if (count > 0) {
                    group.show();
                }
                else {
                    group.hide();
                }
            });

            if (!mainContainer.visible(true)) {
                $.scrollTo(mainContainer, 400, { offset: -50 });
            }
        });

        // Create tooltip for  ExecuteTasks button which informs
        // about plugins to be installed and uninstalled
        btnExecuteTasks.tooltip({
            html: true,
            placement: 'bottom',
            title: function () {
                var text = '';

                if (dropdownUninstall.val()) {
                    text = '<div class="al"><b>@T("Admin.Configuration.Plugins.Fields.Uninstall"):</b></div>';
                    _.each(dropdownUninstall.val(), function (val, i) {
                        text += '<div class="al">{0}</div>'.format(getPluginFriendlyName(dropdownUninstall, val));
                    });
                }

                if (dropdownInstall.val()) {
                    if (text) text += '<div style="height: 6px"></div>';
                    text += '<div class="al"><b>@T("Admin.Configuration.Plugins.Fields.Install"):</b></div>';
                    _.each(dropdownInstall.val(), function (val, i) {
                        text += '<div class="al">{0}</div>'.format(getPluginFriendlyName(dropdownInstall, val));
                    });
                }

                return text;
            }
        });

        // Add/Remove plugins to/from the list of (un)installable plugins
        $('#plugins-form').on('click', 'a.plugin-install, a.plugin-uninstall', function (e) {
            e.preventDefault();

            var el = $(this),
                systemName = el.closest('.module-item').data('system-name'),
                dropdown = null;

            if (el.hasClass("plugin-install")) {
                dropdown = dropdownInstall;
            }
            else if (el.hasClass("plugin-uninstall")) {
                dropdown = dropdownUninstall;
            }

            // set the corresponding dropdown's option to selected
            var wasRemoved = false;
            var option = dropdown.find('option[value="{0}"]'.format(systemName));
            if (option.attr('selected')) {
                option.removeAttr('selected');
                wasRemoved = true;
            }
            else {
                option.attr('selected', 1);
            }

            var transferSrc = wasRemoved ? btnExecuteTasks : el;
            var transferTarget = wasRemoved ? el : btnExecuteTasks;

            transferSrc.stop(true, true).effect("transfer", { to: transferTarget, easing: "easeOutQuad", className: "transfer" }, 400, function () {
                // Toggle the ExecuteTasks button and it's labels
                var labelInstall = btnExecuteTasks.find('.label-install-count'),
                    labelUninstall = btnExecuteTasks.find('.label-uninstall-count'),
                    installCount = dropdownInstall.val() ? dropdownInstall.val().length : 0,
                    uninstallCount = dropdownUninstall.val() ? dropdownUninstall.val().length : 0;

                labelInstall.toggleClass('hide', installCount == 0).text(installCount);
                labelUninstall.toggleClass('hide', uninstallCount == 0).text(uninstallCount);

                if (!installCount && !uninstallCount) {
                    btnExecuteTasks.attr('disabled', 'disabled');
                }
                else {
                    btnExecuteTasks.removeAttr('disabled');
                }
            });

        });

        // Execute the install actions
        btnExecuteTasks.on('click', function (e) {
            var confirmText = '@T("Admin.Configuration.Plugins.ExecuteTasks.Confirm").Text';
            var progressText = '@T("Admin.Configuration.Plugins.ExecuteTasks.Progress").Text';

            if (!confirm(_.str.unescapeHTML(confirmText))) {
                e.preventDefault();
                return false;
            }

            $.throbber.show({
                message: progressText
            });
        });

        // Update (all) plugin resources
        $('#plugins-form').on('click', 'a.plugin-update-resources, a.plugin-update-allresources', function (e) {
            e.preventDefault();
            var el = $(this);

            var confirmText = '@T("Admin.Configuration.Plugins.Resources.UpdateConfirm").Text',
                confirmAllText = '@T("Admin.Configuration.Plugins.Resources.UpdateAllConfirm").Text',
                progressText = '@T("Admin.Configuration.Plugins.Resources.UpdateProgress")';

            if (!confirm(_.str.unescapeHTML(el.hasClass('plugin-update-allresources') ? confirmAllText : confirmText))) {
                return false;
            }

            $.throbber.show({
                message: progressText,
                callback: function () {
                    setLocation(el.attr("href"));
                }
            });
        });

        $('#plugins-form').on('click', '.plugin-edit', function (e) {
            OpenWindow(
                '{0}?systemName={1}&btnId=btnRefresh&formId=plugins-form'.format(
                    '@Url.Content("~/Admin/Plugin/EditPopup")',
                    $(this).data("systemname")
                ),
                1000,
                480,
                true
            );
            return false;
        });

        $('#btnRefresh').click(function () {
            // reload page
            setLocation(location.href);
            return false;
        });
    });
</script>
@*@Html.Action("UploadPackage", "Packaging", new { isTheme = false })*@


